#include "rtp/SenderReport.h"

#include <cstdint>
#include <cstring>
#include <memory>

namespace Rtp {
    namespace Rtcp {
        SenderReport* SenderReport::Parse(const uint8_t *data, size_t len) {
            auto *header = const_cast<Header *>(reinterpret_cast<const Header *>(data));
            if (len < HeaderSize) {
                return nullptr;
            }

            return new SenderReport(header);
        }

        void SenderReport::Dump() const {}

        size_t SenderReport::Serialize(uint8_t *buffer) {
            std::memcpy(buffer, this->header, HeaderSize);

            return HeaderSize;
        }

        SenderReportPacket* SenderReportPacket::Parse(const uint8_t *data, size_t len) {
            auto *header = const_cast<CommonHeader *>(reinterpret_cast<const CommonHeader *>(data));

            std::unique_ptr<SenderReportPacket> packet(new SenderReportPacket(header));

            const size_t offset = Packet::CommonHeaderSize;

            SenderReport *report = SenderReport::Parse(data + offset, len - offset);

            if (report) {
                packet->AddReport(report);
            }
            return packet.release();
        }

        size_t SenderReportPacket::Serialize(uint8_t *buffer) const {
            size_t offset { 0 };
            uint8_t *header { nullptr };
            for (auto *report : this->reports) {
                header = buffer + offset;
                // 序列化 RTCP 通用头部    
                offset += Packet::Serialize(buffer + offset); // 写入版本、填充位、类型等
                offset += report->Serialize(buffer + offset); // 写入SR的具体数据

                reinterpret_cast<Packet::CommonHeader *>(header)->count = 0;

                size_t length = Packet::CommonHeaderSize;
                length += SenderReport::HeaderSize;

                reinterpret_cast<Packet::CommonHeader *>(header)->length = uint16_t { htons((length / 4) - 1)};
            }

            return offset;
        }

        void SenderReportPacket::Dump() const {

        }
    }
}